package com.beiding.natgo.client;

import com.alibaba.fastjson.JSONObject;
import com.beiding.natgo.common.Message;
import com.beiding.natgo.config.ServerConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.websocket.*;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;

@ClientEndpoint
@Slf4j
public class Cep {

    private SessionManager sessionManager;

    private ClientConfig clientConfig;

    private Runnable retry;

    public void setClientConfig(ClientConfig clientConfig) {
        this.clientConfig = clientConfig;
    }

    @OnOpen
    public void onOpen(Session session) {
        this.sessionManager = new SessionManager();
        log.info("连接成功");
        sessionManager.intSession(session, clientConfig);
        this.sessionManager.start();
        log.info("初始化服务端口  {}", clientConfig.getServerPort());
        sessionManager.getSessionHolder().sendInitPort();
    }

    @OnClose
    public void onClose(Session session) throws InterruptedException {
        if (sessionManager != null) {
            sessionManager.stop();
            sessionManager = null;
        }

        log.info("连接被迫关闭");
        retry.run();
    }

    @OnMessage
    public void onMessage(Session session, InputStream inputStream) {
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
            Message message = (Message) objectInputStream.readObject();
           // log.info("收到消息 type={}  msg={}", message.getType(), message.getMsg());
            sessionManager.handleMessage(session, message);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void setRetry(Runnable retry) {
        this.retry = retry;
    }
}
